<?php

namespace catchAdmin\externalGoods\service;

use catchAdmin\externalGoods\model\Areas;
use catchAdmin\externalGoods\model\Category as externalCategoryModel;
use catchAdmin\externalGoods\model\GoodsAttribute as externalGoodsAttribute;
use catchAdmin\externalGoods\model\Category as CategoryModel;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\Code;
use houniao\api\v1\Goods;
use think\Exception;
use think\facade\Db;

class CategoryService{

    protected $user;
    protected $redis;
    protected $redisKey = 'disabled_categories';

//    public function __construct()
//    {
//        $user = (new CatchAuth())->user();
//        $this->user = $user;
//    }

    public function __construct()
    {
        // 初始化Redis连接
        $this->redis = new \Redis();
        $this->redis->connect('127.0.0.1', 6379);
        $this->redis->auth(config('cache.stores.redis.password'));
    }

    /**
     * 获取禁用分类列表
     * @return array
     */
    public function getDisabledCategories()
    {
        try {
            // 优先从Redis获取
            $categoryIds = $this->redis->get($this->redisKey);
            if ($categoryIds !== false) {
                return json_decode($categoryIds, true);
            }
            
            // Redis没有则从数据库获取
            $disabledCategoriesModel = new \catchAdmin\externalGoods\model\DisabledCategories();
            $categoryIds = $disabledCategoriesModel->getDisabledCategoryIds();
            
            // 缓存到Redis
            $this->redis->set($this->redisKey, json_encode($categoryIds));
            
            return $categoryIds;
        } catch (\Exception $e) {
            throw new \Exception('获取禁用分类失败: ' . $e->getMessage());
        }
    }

    //列表
    public function getTreeList(){
        $list = (new CategoryModel)->getList();

        $result = $this->generateTree($list,0);
        return $result;
    }

    //远程和本地数据简单对比
    public function check($param){
        //远程数据
        $pages = $param['pages'];
        $data = $param['data'];

        if(0 == $pages['total']){
            return CatchResponse::fail('total:0');
        }

        //远程商品本地商品对比
        $data =  $this->remoteLocalCheck(['goods_data'=>$data],'all')['goods_data'];

        return json([
            'code'    => Code::SUCCESS,
            'message' => 'success',
            'count'   => $pages['total'],
            'current' => $pages['current_page'],
            'limit'   => $pages['page_size'],
            'data'    => $data
        ]);
    }

    //同步
    public function sync($param,$supplier_id = 1){
        if(empty($param)){
            return CatchResponse::fail('没有数据');
        }

        $param  = $this->array_flatten($param);
        $data['goods_category_data'] = $param;

        Db::startTrans();
        try {
            //删除之前供应商分类
            $this->deleteAllCategoryBySupplierId($supplier_id);

            //批量添加商品分类
            $this->batchDealGoodsCategory($data,$supplier_id);

            Db::commit();
            return CatchResponse::success([],'分类同步成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('同步失败' . json_encode($exception->getTrace()));
        }
    }

    public function array_flatten($array,$key = 'children') {

        $result = [];
        foreach ($array as $k1 => &$v1) {
            $v1['level'] = 1;
            $result[] = $v1;
            if(!array_key_exists($key,$v1) || empty($v1[$key])){
                continue;
            }

            foreach ($v1[$key] as $k2 => &$v2){
                $v2['level'] = 2;
                $result[] = $v2;
                if(!array_key_exists($key,$v2) || empty($v2[$key])){
                    continue;
                }

                foreach ($v2[$key] as $k3 => &$v3){
                    $v3['level'] = 3;
                    $result[] = $v3;
                }
            }

        }
        return $result;
    }

    public function makeTree($data)
    {

        $res = [];
        $tree = [];

        // 整理数组
        foreach ($data as $key => $vo) {
            $res[$vo['id']] = $vo;
        }
        unset($data);

        // 查询子孙
        foreach ($res as $key => $vo) {
            if ($vo['pid'] != 0) {
                $res[$vo['pid']]['child'][] = &$res[$key];
            }
        }

        // 去除杂质
        foreach ($res as $key => $vo) {
            if ($vo['pid'] == 0) {
                $tree[] = $vo;
            }
        }
        unset($res);

        return $tree;
    }

    public function generateTree($data,$parent_id = 0,$id = 'id')
    {
        $tree = [];
        $newData = array_combine(array_column($data,$id),$data);

        foreach ($newData as $key => $datum) {
//            $newData[$key]['value'] = $datum['id'];
//            $newData[$key]['label'] = $datum['name'];
            if ($datum['pid'] == $parent_id) {
                //根节点直接把地址放到新数组中
                $tree[] = &$newData[$key];
            } else {
                //不是根节点的将自己的地址放到父级的child节点
                $newData[$datum['pid']]['children'][] = &$newData[$key];
                //$newData[$datum['parent_id']]['son'][] = &$newData[$key];
            }
        }
        return $tree;
    }

    private function deleteAllCategoryBySupplierId($id = 1){

        $res =  Db::table('db_syst_sync_goods_category')
            ->where('supplier_id',$id)
            ->delete();

        return $res;
    }

    //处理批量供应商商品分类
    private function batchDealGoodsCategory($param,$supplier_id=1)
    {
        $categoryArr = [];
        foreach ($param['goods_category_data'] as $value){
            $data = [];
            $data['cate_id'] = (string) $value['id'];
            $data['pid'] = $value['pid'];
            $data['level'] = $value['level'];
            $data['name'] = $value['name'];
            $data['image'] = $value['image'];

            $data['supplier_id'] = $supplier_id;
            $data['creator_id'] = $this->user['id'];
            $categoryArr[] = $data;
        }

        Db::startTrans();
        try {
            //添加属性
            $categoryModel = (new externalCategoryModel());
            $categoryModel->saveAll($categoryArr);

            Db::commit();
            return $param;
        } catch (\Exception $exception) {
            Db::rollback();
            throw new Exception('供应商分类添加失败');
        }
    }

    public function get_all_child_cate($catid,$str = ''){
        $model = new CategoryModel;
        $child =  $model->where('pid',$catid)->column('id');

        if($child){
            $str .= ",".implode(',',$child);
            foreach($child as $key => $val){
                $str = $this->get_all_child_cate($val,$str);
            }
        }
        return trim($str,',');
    }
}